<template>
  <div class="elm-edit f_edit">
    <elm-page-bb class="ei_edit" v-loading="loading">

      <el-card shadow="hover" class="e_card_01" style="height: 180px;">
        <div slot="header">
          <span style="font-weight: bold;">流程信息</span>
        </div>
        <el-form ref="model" :model="model" size="small" label-width="120px">
          <elm-row>
            <el-form-item label="名称" prop="title" :rules="[{ required: true, message: '名称 必须填写'}]">
              <el-input v-model="model.title"></el-input>
            </el-form-item>
          </elm-row>
          <elm-row>
            <el-form-item label="编码" prop="code" :rules="[{ required: true, message: '编码 必须填写'}]">
              <el-input v-model="model.code" v-if="flowExist" disabled style="width: 300px;"></el-input>
              <el-input v-model="auto_code_text" v-if="auto_code && !flowExist" disabled style="width: 300px;"></el-input>
              <el-input v-model="model.code"  v-if="!auto_code && !flowExist"style="width: 300px;"></el-input>
              <el-button @click="auto_code=false" v-if="auto_code && !flowExist" type="text" size="mini"
                         style="margin-left: 10px;">手动编辑</el-button>
            </el-form-item>
          </elm-row>
          <elm-row>
            <el-form-item label="顺序" prop="order_number">
              <el-input v-model="model.order_number"></el-input>
            </el-form-item>
          </elm-row>
          <elm-row v-if="false">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="2" v-model="model.remark"></el-input>
            </el-form-item>
          </elm-row>
        </el-form>
      </el-card>

      <el-row style="height:calc(100% - 200px);">
        <el-col :span="12"  style="height:100%;">
          <el-card shadow="hover" class="e_card_02"  style="height:100%;">
            <div slot="header">
              <span style="font-weight: bold;">流程绘制</span>
              <elm-open-button url="flow_canvas" :full="true" width="90%" height="90%" icon="el-icon-edit" size="mini"
                               :data="{'flow_model':model,'param_list':paramList,'ff_item_list':this.ffItemList}" :disabled="paramListLoading"
                               title="绘制" style="float: right;margin-top: -4px;">画布</elm-open-button>
            </div>

            <!--注意，elm-flow-canvas-show 组件中若有跟flow_canvas页中id相同的元素，或同名但内容不同的css类，可能导致flow_canvas页无法正常显示-->
            <!--所以，elm-flow-canvas-show 组件中添加连线时，使用的id与flow_canvas页中不同，这也在连线悬停处理函数中有体现-->
            <div v-if="flowExist" style="width: 100%;height: calc(100% - 10px);">
              <elm-flow-canvas-show :flow_id="model.id"></elm-flow-canvas-show>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12"  style="height:100%;">
          <el-card shadow="hover" class="e_card_03"   style="height:100%;">
            <div slot="header">
              <span style="font-weight: bold;">流程表单</span>
              <span style="float: right;" v-if="!flowExist && em(model.table_name)">
            <span style="font-weight: normal;">自定义表名：</span>
            <el-input v-model="model.secForm_tableName" v-if="flowExist" disabled style="width: 220px;" size="mini"></el-input>
            <el-input v-model="auto_secForm_text" v-if="auto_secForm_table && !flowExist" disabled style="width: 220px;" size="mini"></el-input>
            <el-input v-model="model.secForm_tableName"  v-if="!auto_secForm_table && !flowExist"style="width: 220px;" size="mini"></el-input>
            <el-button @click="auto_secForm_table=false" v-if="auto_secForm_table && !flowExist" type="text" size="mini"
                       style="margin-left: 10px;">手动编辑</el-button>
            </span>
              <span style="float: right;margin-top: 5px;" v-if="flowExist || !em(model.table_name)">
              <span v-show="false" style="font-weight: normal;">表单表名：{{model.table_name}}</span>
            </span>
            </div>
            <el-row style="text-align: right;padding: 3px;height: 35px;">
              <elm-open-button url="one_road_flowsec_form_s" :full="false"  width="1000" height="90%" size="mini"
                               title="预览" :data="{'page_type':'template','flow_code':model.code}"
                               type="text" style="font-size: 14px;"
                               v-if="flowExist || !em(model.table_name)">预览</elm-open-button>
              <elm-open-button url="one_road_flow_form_edit" :full="false" width="700" height="450" icon="el-icon-edit" size="mini"
                               :data="{'edit_type':'create','flow_model':model,'on_canvas':'yes'}" v-loading="ffItemListLoading"
                               title="表单项">新增</elm-open-button>
            </el-row>
            <el-row v-loading="ffItemListLoading" style="height: calc(100% - 45px);display: flex;">
              <elm-table :data='ffItemList' :stripe='true' :border='true' size='mini' :page-size="9999" height="100%">
                <el-table-column label="标题" min-width="100px" header-align="center">
                  <template slot-scope="scope">
                    {{scope.row.title}}
                    <span v-if="scope.row.e_require" style="color: #409EFF;margin-left: 5px;">[必填]</span>
                    <span v-if="scope.row.e_number" style="color: #409EFF;margin-left: 5px;">[数字]</span>
                  </template>
                </el-table-column>
                <el-table-column label="类型" width="70px" align="center">
                  <template slot-scope="scope">
                    {{scope.row.type_name}}
                  </template>
                </el-table-column>
                <!--<el-table-column prop="remark" label="备注" min-width="60px" header-align="center"></el-table-column>-->
                <el-table-column label="操作" width="160px" fixed="right" align="center">
                  <template slot-scope="scope">
                    <el-button @click="v_moveItem_ffItem(scope.row,'up')" type="text" size="mini"
                               :disabled="scope.$index==0">
                      上移</el-button>
                    <el-button @click="v_moveItem_ffItem(scope.row,'down')" type="text" size="mini"
                               :disabled="scope.$index==ffItemList.length-1">
                      下移</el-button>
                    <elm-open-button url="one_road_flow_form_edit" :full="false" width="700" height="450" type="text" size="mini"
                                     :data="{'model':scope.row,'flow_model':model}" title="表单项">
                      编辑</elm-open-button>
                    <el-button @click="v_deleteFFItem(scope.row)" type="text" size="mini" >
                      删除</el-button>
                  </template>
                </el-table-column>
              </elm-table>
            </el-row>
          </el-card>
        </el-col>
        <el-col v-if="false" :span="12"  style="height:100%;">
          <el-card shadow="hover" class="e_card_02"  style="height:100%;">
            <div slot="header">
              <span style="font-weight: bold;">流程参数与绘制</span>
            </div>
            <el-row style="text-align: right;height: 35px;padding: 3px;">
              <elm-open-button url="flow_param_edit" :full="false" width="600" height="300" icon="el-icon-edit" size="mini"
                               :data="{'edit_type':'create','flow_model':model}" :disabled="paramListLoading"
                               title="流程参数">新增参数</elm-open-button>
              <elm-open-button url="flow_canvas" :full="true" width="90%" height="90%" icon="el-icon-edit" size="mini"
                               :data="{'flow_model':model,'param_list':paramList}" :disabled="paramListLoading"
                               title="绘制">画布</elm-open-button>
            </el-row>
            <el-row v-loading="paramListLoading" style="display: flex;height: calc(100% - 45px);width: calc(100% - 5px);">
              <elm-table :data='paramList' :stripe='true' :border='true' size='mini' :page-size="9999" height="100%">
                <el-table-column prop="param_name" label="参数名称" min-width="100px" header-align="center"></el-table-column>
                <el-table-column prop="param_value" label="默认值" width="80px" align="center"></el-table-column>
                <el-table-column prop="param_explain" label="备注" width="60px" header-align="center"></el-table-column>
                <el-table-column label="操作" width="160px" fixed="right" align="center">
                  <template slot-scope="scope">
                    <elm-open-button url="flow_param_edit" :full="false" width="700" height="450" type="text" size="mini"
                                     :data="{'model':scope.row,'flow_model':model}" title="流程参数">
                      编辑</elm-open-button>
                    <el-button @click="v_deleteParam(scope.row)" type="text" size="mini" >
                      删除</el-button>
                  </template>
                </el-table-column>
              </elm-table>
            </el-row>
          </el-card>
        </el-col>
      </el-row>


      <template #bottom>
        <el-button type="success" size="small" @click="submit">立即保存</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </template>
    </elm-page-bb>
  </div>
</template>

<script>
export default {
  extends: elmVueBase,
  data() {
    return {
      loading:true,

      DE_INFO: null,
      edit_type: '',

      model: {},
      flowExist:false,
      auto_code:true,
      auto_code_text:'自动生成',
      auto_secForm_text:'自动生成：biz_ + 流程编码',
      auto_secForm_table:true,

      paramListLoading:true,
      paramList:[],

      ffItemListLoading:true,
      ffItemList:[],
    }
  },
  mounted() {
    this.DE_INFO = elm.dialog.request;
    this.edit_type = this.DE_INFO.edit_type;

    this.v_getData();
  },
  methods: {
    async v_getData(){
      this.loading = true;

      this.paramList = [];
      this.ffItemList = [];
      if(this.edit_type=='create'){
        this.model = {id: elm.newGuid()};
        this.paramListLoading = false;
        this.ffItemListLoading = false;
      }
      else{
        this.flowExist = true;
        this.model = this.DE_INFO.model;

        this.v_getParamList();
        this.v_getffItemList();
      }

      this.loading = false;
    },
    async v_getParamList(){
      this.paramListLoading = true;
      //查找并组装节点数据
      let paramList = [];
      //paramList = await elm.post('/system/login/flow/GetFlowParamList', { "flow_id": this.model.id});
      //if(paramList.length>0){}
      this.paramList = paramList;
      this.paramListLoading = false;
    },
    async v_getffItemList(){
      this.ffItemListLoading = true;
      //查找并组装表单数据
      this.ffItemList=[];
      let fList = await elm.post('/system/login/flow/GetSecForm', { "flow_id": this.model.id});
      if(fList.length>0 && fList[0]!=null){
        let dd = fList[0].table_column;
        if(!this.em(dd)){
          let ffItemList=JSON.parse(dd);
          let ttt = {
            'input':'填写',
            'date':'日期',
            'time':'时间',
            'datetime':'日期时间',
            'text':'文本',
            'select':'选择',
            'file':'附件',
            'bx_item':'报销项',
            'select_input_pj':'关联项目',
            'select_org':'选择部门',
            'select_ei':'选择人员',
            'select_user':'选择账号',
            'select_car':'选择车辆',
            'select_input_xs':'关联线索',
            'select_input_sj':'关联商机',
            'select_input_pu':'采购信息',
          };
          for(let i=0;i<ffItemList.length;i++){
            ffItemList[i]['type_name'] = ttt[ffItemList[i].type];
          }
          this.ffItemList=ffItemList;
        }
      }
      this.ffItemListLoading = false;
    },
    async setFLowExist(d){
      if(d){
        ///按id重新获取model数据
        let check = await elm.post('/system/login/flow/GetFlowList', { "id": this.model.id});
        if (check.length>0) {
          this.model = check[0];
          if(!this.flowExist){
            this.flowExist = true;
            this.DE_INFO.callVue.v_getData();
          }
        }
      }
      this.flowExist= d ;
    },

    async submit() {
      //若无流程编码，自动生成一个
      this.loading = true;
      if(this.em(this.model.code)){
        let cData = await elm.post('/system/login/flow/GetFlowCodeForCreate', {});
        if(this.em(cData.code) || cData.code.indexOf('flow_')<0){
          this.$message.error('流程编码生成失败，请稍后尝试。');
          this.loading = false;
          return;
        }
        this.model.code = cData.code;
      }
      if(this.em(this.model.order_number)){this.model.order_number = this.model.code;}
      this.loading = false;

      try{await this.$refs["model"].validate();}catch{console.log('表单验证未通过'); return;}

      this.loading = true;
      let check = await elm.post('/system/login/flow/GetFlowList', { "code": this.model.code});
      if (check.length>0 && check[0].id !=this.model.id) { this.$message.error('流程编码重复'); this.loading = false;return;}
      else {
        if(!this.em(this.model.secForm_tableName)){
          this.model['ff_tablename'] = 'biz_'+this.model.secForm_tableName;
        }
        else{ this.model['ff_tablename'] = 'biz_'+this.model.code; }

        this.model['on_canvas'] = 'yes';
        let result = await elm.post('/system/login/flow/UpserFlowAndSecForm', {'model':this.model});
        if (result == true) {
          this.$message({ type: 'success', message: '保存成功' });
          this.DE_INFO.callVue.v_getData();
          this.v_cancle();
        }
        else { this.$message.error('保存失败，请稍后尝试。'); }
        this.loading = false;
      }
    },
    v_cancle(){
      this.close();//extends: elmVueBase
    },

    async v_deleteParam(data){
      await elm.delete('/system/login/flow/DeleteParam', {'id':data.id});
      this.v_getParamList();
    },

    async v_moveItem_ffItem(item, type){
      let newList = this.v_moveItem(this.ffItemList,item,type);
      let pData = {
        'flow_id':this.model.id,
        'flow_code':this.model.code,
        'form_item':newList,
        'form_item_str':JSON.stringify(newList),
      };
      await elm.post('/system/login/flow/UpsertFlowSecForm', pData);
      this.v_getffItemList();
    },
    v_moveItem(tList, item, type) {
      if (tList == null || tList.length == 0 || (type != 'up' && type != 'down')) { return; }

      let index = -1;
      let id = item.id;
      for (let i = 0; i < tList.length; i++) {
        if (id == tList[i].id) {index = i;}
      }
      if ((index == 0 && type == 'up') || (index >= (tList.length - 1) && type == 'down')) { return; }

      let newList = [];
      let tIndex = type == 'up' ? (index - 1) : (index + 1);
      for (let i = 0; i < tList.length; i++) {
        if (i != index && i != tIndex) { newList.push(tList[i]); }
        else if (i == index) { newList.push(tList[tIndex]); }
        else if (i == tIndex) { newList.push(tList[index]); }
      }

      return newList;
    },

    async v_addOne_ffItem(item){
      this.ffItemListLoading = true;

      //生成新的列名
      if(this.ffItemList.length==0){
        item['column_name'] = 'col_1';
      }
      else{
        let tNum = this.ffItemList.length + 1;
        for (let i = 0; i < this.ffItemList.length; i++) {
          let eNum = this.ffItemList[i].column_name.split('_');
          eNum = parseInt(eNum[1]);
          if(tNum<=eNum){tNum = eNum+1;}
        }

        item['column_name'] = 'col_'+tNum;
      }

      item['column_change'] = 'add';

      this.ffItemList.push(item);
      let newList = this.ffItemList;

      let pData = {
        'flow_id':this.model.id,
        'flow_code':this.model.code,
        'form_item':[item],
        'form_item_str':JSON.stringify(newList),
      };
      await elm.post('/system/login/flow/UpsertFlowSecForm', pData);
      this.v_getffItemList();
    },
    async v_changeOne_ffItem(item){
      this.ffItemListLoading = true;

      item['column_change'] = 'change_type';

      for (let i = 0; i < this.ffItemList.length; i++) {
        if (this.ffItemList[i].id == item.id) { this.ffItemList[i]=item; break; }
      }
      let newList = this.ffItemList;

      let pData = {
        'flow_id':this.model.id,
        'flow_code':this.model.code,
        'form_item':[item],
        'form_item_str':JSON.stringify(newList),
      };
      await elm.post('/system/login/flow/UpsertFlowSecForm', pData);
      this.v_getffItemList();
    },
    async v_deleteFFItem(item){
      this.ffItemListLoading = true;

      item['column_change'] = 'delete';

      let tList = this.ffItemList;
      if (tList == null || tList.length == 0) { return; }

      let id = item.id;
      let newList = [];
      for (let i = 0; i < tList.length; i++) {
        if (tList[i].id!=id){newList.push(tList[i]);}
      }

      let pData = {
        'flow_id':this.model.id,
        'flow_code':this.model.code,
        'form_item':[item],
        'form_item_str':JSON.stringify(newList),
      };
      await elm.delete('/system/login/flow/UpsertFlowSecForm', pData);
      this.v_getffItemList();
    },

    em(s) {
      if (s == null || s == '') { return true; }
      else { return false; }
    },

  }
}
</script>
<style>
.f_edit .elm-body{padding: 5px;}
.f_edit .e_card_01 .el-card__body{height:calc(100% - 3px);}
.f_edit .e_card_02 .el-card__body{height: calc(100% - 40px);margin-left: 0px;}
.f_edit .e_card_03 .el-card__body{height:calc(100% - 40px);  margin-right: 0px;}
.f_edit .e_card_02{margin-left: 0px !important;}
.f_edit .e_card_03{margin-right: 0px !important;}
</style>